package com.sitech.ibnms.c3p.util;

import org.apache.ignite.cache.spring.SpringCacheManager;
import org.jsr166.ConcurrentHashMap8;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.Collection;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by leo on 16/2/25.
 */
public class IgniteSpringCacheManager implements CacheManager {
    private final ConcurrentMap<String, MyCache> caches = new ConcurrentHashMap8<String, MyCache>();

    private final SpringCacheManager cacheManager;

    public IgniteSpringCacheManager(SpringCacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @Override
    public Cache getCache(String name) {
        MyCache cache = caches.get(name);
        if (cache == null) {
            cache = new MyCache(cacheManager.getCache(name));
            MyCache old = caches.putIfAbsent(name, cache);
            if (old != null) cache = old;
        }
        return cache;
    }

    @Override
    public Collection<String> getCacheNames() {
        return cacheManager.getCacheNames();
    }

    public static class MyCache implements Cache {
        private final Cache cache;

        public MyCache(Cache cache) {
            this.cache = cache;
        }

        @Override
        public String getName() {
            return cache.getName();
        }

        @Override
        public Object getNativeCache() {
            return cache.getNativeCache();
        }

        @Override
        public ValueWrapper get(Object key) {
            return cache.get(key);
        }

        @Override
        public <T> T get(Object key, Class<T> type) {
            return cache.get(key, type);
        }

        @Override
        public void put(Object key, Object value) {
            if (key != null && value != null)
                cache.put(key, value);
        }

        @Override
        public ValueWrapper putIfAbsent(Object key, Object value) {
            return cache.putIfAbsent(key, value);
        }

        @Override
        public void evict(Object key) {
            cache.evict(cache);
        }

        @Override
        public void clear() {
            cache.clear();
        }
    }
}
